package reggex;

import java.util.List;

import lexer.Token;
import parser.SyntaxTranslator;
import parser.Production;
import parser.SemanticProduction;

import automaton.NondeterministicAutomaton;
import automaton.NDState;


/**
 * Traductor dirigido por la sintaxis que sintetiza ReggexAttribute's,
 * construyendo un autómata no determinístico a partir de una expresión regular.
 */
public class ReggexTranslator implements SyntaxTranslator<ReggexAttributes> {
	
	public ReggexAttributes translateTerminal(Token t) {
		if(t.getId() == ReggexTokenizer.CHAR_ID) {
			return new ReggexAttributes(getCharacterAutomaton(t));
		} else {
			return new ReggexAttributes(t);
		}
	}
	
	public ReggexAttributes translateNonterminal(Production p, List<ReggexAttributes> children) {
		return ((SemanticProduction<ReggexAttributes>)p).synthesize(children);
	}
	
	private NondeterministicAutomaton<Character> getCharacterAutomaton(Token t) {
		NDState<Character> s1 = new NDState<Character>(false);
		NDState<Character> s2 = new NDState<Character>(true);
		
		if(".".equals(t.getValue())) {
			for(int i = 0; i < ReggexTokenizer.ALL_CHARACTERS.length(); i++)
				s1.addTransition(ReggexTokenizer.ALL_CHARACTERS.charAt(i), s2);
		} else {
			s1.addTransition(t.getValue().charAt(0), s2);
		}
		
		NondeterministicAutomaton<Character> ret =
			new NondeterministicAutomaton<Character>(s1);
		
		ret.addState(s2);
		
		return ret;
	}
}
